package cc.comac.mom.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cc.comac.mom.api.EquipSparePartMasterDataService;
import cc.comac.mom.bean.EquipSparePartMasterData;
import cc.comac.mom.bean.ResultDev;
import cc.comac.mom.datahandlers.entity.EquipSparePartMasterDataDataHandler;
import cc.comac.mom.datahandlers.entity.EquipSparePartsTypeDataHandler;
import cc.comac.mom.entity.EquipSparePartMasterDataEntity;
import cc.comac.mom.entity.EquipSparePartsTypeEntity;
import cc.comac.mom.util.ExcelUploadUtil;
import cc.comac.mom.util.ExportExcel;
import cc.comac.mom.util.ResultBean;
@Service
@RestController
public class EquipSparePartMasterDataServiceImpl implements EquipSparePartMasterDataService {

	@Autowired
	private EquipSparePartMasterDataDataHandler equipSparePartMasterDataDataHandler;
	@Autowired
	private EquipSparePartsTypeDataHandler equipSpareSartsTypeDataHandler;
	
	@Override
	public ResultBean insertSaprePartMasterData(@RequestBody EquipSparePartMasterData equipSparePartMasterData) {
		
		return equipSparePartMasterDataDataHandler.insertSaprePartMasterData(equipSparePartMasterData);
	}

	@Override
	public ResultBean updateSparePart(@RequestBody EquipSparePartMasterData equipSparePartMasterData) {
		// TODO Auto-generated method stub
		return equipSparePartMasterDataDataHandler.updateSparePart(equipSparePartMasterData);
	}

	@Override
	public ResultBean batchDelete(@RequestBody List<EquipSparePartMasterData> list) {
		// TODO Auto-generated method stub
		return equipSparePartMasterDataDataHandler.batchDelete(list);
	}

	@Override
	public ResultDev selectBysomeField(@RequestBody EquipSparePartMasterData equipSparePartMasterData) {
		ResultDev resultDev = new ResultDev();
		if (equipSparePartMasterData.getSearchAll() != 1) {
			resultDev = equipSparePartMasterDataDataHandler.selectBysomeField(equipSparePartMasterData);
		}else {
			resultDev = equipSparePartMasterDataDataHandler.selectAll();
		}
		return resultDev;
	}

	@Override
	public ResultBean selectBysparePartNumber(@RequestBody EquipSparePartMasterData equipSparePartMasterData) {
		
		return equipSparePartMasterDataDataHandler.selectBysparePartNumber(equipSparePartMasterData);
	}

	@Override
	public ResultDev selectByWarehouseName(@RequestBody EquipSparePartMasterData equipSparePartMasterData) {
		
		return equipSparePartMasterDataDataHandler.selectByWarehouseName(equipSparePartMasterData);
	}

	@Override
	public ResultBean selectByWarehouseNameAndSpareNumber(@RequestBody EquipSparePartMasterData equipSparePartMasterData) {
		return equipSparePartMasterDataDataHandler.selectByWarehouseNameAndSpareNumber(equipSparePartMasterData);
	}

	@Override
	public ResultBean importSparePartMasterData(@RequestPart("file") MultipartFile file, @RequestParam String rootPath) throws IOException {
		
		ResultBean resultBean = new ResultBean(true);
//		if (file == null || file.isEmpty()) {
//			resultBean.setSuccess(false);
//			resultBean.setMessage("上传失败，请重新上传！");
//			return resultBean;
//		} else if (file.getSize() > 10000000) {
//			resultBean.setSuccess(false);
//			resultBean.setMessage("上传失败，文件大小不能超过10M!！");
//			return resultBean;
//		}
//		String fileName = file.getOriginalFilename();
//		File dir = new File(rootPath);
//		if (!dir.exists()) {
//			dir.mkdir();
//		}
//		File chunkFile = new File(dir, fileName);
//		try {
//			chunkFile.createNewFile();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		file.transferTo(chunkFile);
		
		//已存在备件编号数据集合
		ArrayList<String> listPartNumber = new ArrayList<String>();
		//已存在备件类型名称
		ArrayList<String> listPartTypeNumber = new ArrayList<String>();
		//新增的数据集合
		ArrayList<EquipSparePartMasterDataEntity> listNewPartMasterDataEntity = new ArrayList<EquipSparePartMasterDataEntity>();
		//查询数据库存在的备件编码，添加到已存在的数据集合里
    	QueryWrapper<EquipSparePartMasterDataEntity> queryWrapper = new QueryWrapper<EquipSparePartMasterDataEntity>();
    	queryWrapper.eq("row_status",1);
    	List<EquipSparePartMasterDataEntity> listPartMasterDataEntity = equipSparePartMasterDataDataHandler.list(queryWrapper);
    	if(listPartMasterDataEntity != null && listPartMasterDataEntity.size()>0) {
    		for(EquipSparePartMasterDataEntity item :listPartMasterDataEntity) {
    			listPartNumber.add(item.getSparePartNumber());
    		}
    	}
    	//查询已存在的备件类型
    	QueryWrapper<EquipSparePartsTypeEntity> queryWrapper2 = new QueryWrapper<EquipSparePartsTypeEntity>();
    	queryWrapper2.eq("row_status",1);
    	List<EquipSparePartsTypeEntity> listEquipSparePartsTypeEntity = equipSpareSartsTypeDataHandler.list(queryWrapper2);
    	if(listEquipSparePartsTypeEntity != null && listEquipSparePartsTypeEntity.size()>0) {
    		for(EquipSparePartsTypeEntity item:listEquipSparePartsTypeEntity) {
    			listPartTypeNumber.add(item.getCategoryNumber());
    		}
    	}
		try {
		//	FileInputStream in = new FileInputStream(file);
//			FileInputStream in = new FileInputStream(chunkFile);
			Workbook workbook;
			try {
				workbook = ExcelUploadUtil.getWorkBook(file);
				// Sheet的数量
				int sheetCount = workbook.getNumberOfSheets();
				//循环sheet
				for(int i = 0;i<sheetCount ; i++) {
					Sheet sheetAt = workbook.getSheetAt(i);
					//行数
					int rowCount = sheetAt.getLastRowNum();
					System.out.println(rowCount+"行数");
					if(rowCount<1) {
						continue;
					}
					//循环行
					for(int j = 1;j<=rowCount;j++) {
						Row row = sheetAt.getRow(j);
						int cellCount = row.getPhysicalNumberOfCells();
						System.out.println(cellCount+"列数");
						Cell cell0 = row.getCell(0);
						Object sparePartNumber = ExcelUploadUtil.getValue(cell0);
						//数据为空
						if(sparePartNumber == null) {
							continue;
						}
						//数据已存在
						if(listPartNumber.contains(sparePartNumber)) {
							continue;
						}
						Object sparePartType = ExcelUploadUtil.getValue(row.getCell(1));
						if(sparePartType == null) {
							continue;
						}
						if(!listPartTypeNumber.contains(sparePartType)) {
							continue;
						}
						Object sparePartName = ExcelUploadUtil.getValue(row.getCell(2));
						if(sparePartName == null) {
							continue;
						}
						Object sparePartModel = ExcelUploadUtil.getValue(row.getCell(3));
						Object supplierName = ExcelUploadUtil.getValue(row.getCell(4));
						Object price = ExcelUploadUtil.getValue(row.getCell(5));
						Object upperLimit = ExcelUploadUtil.getValue(row.getCell(6));
						Object lowerLimit = ExcelUploadUtil.getValue(row.getCell(7));
						Object totalAmount = ExcelUploadUtil.getValue(row.getCell(8));
						Object sparePartsUnit = ExcelUploadUtil.getValue(row.getCell(9));
						Object importantParam = ExcelUploadUtil.getValue(row.getCell(10));
						Object description = ExcelUploadUtil.getValue(row.getCell(11));

						
						EquipSparePartMasterDataEntity partMasterEntity = new EquipSparePartMasterDataEntity();
						partMasterEntity.setSparePartNumber(sparePartNumber.toString());
						partMasterEntity.setSparePartType(sparePartType.toString());
						partMasterEntity.setSparePartName(sparePartName.toString());						
						if(sparePartModel != null) {
							partMasterEntity.setSparePartModel(sparePartModel.toString());
						}
						if(supplierName != null) {
							partMasterEntity.setSupplierName(supplierName.toString());
						}
						if(price != null) {
							partMasterEntity.setPrice(Double.valueOf(price.toString()));
						}
						if(upperLimit != null) {
							partMasterEntity.setUpperLimit(Double.valueOf(upperLimit.toString()));
						}
						if(lowerLimit != null) {
							partMasterEntity.setLowerLimit(Double.valueOf(lowerLimit.toString()));
						}
						if(totalAmount != null) {
							partMasterEntity.setTotalAmount(Double.valueOf(totalAmount.toString()));
						}						
						if(sparePartsUnit != null) {
							partMasterEntity.setSparePartsUnit(sparePartsUnit.toString());
						}
						if(importantParam != null) {
							partMasterEntity.setImportantParam(importantParam.toString());
						}
						if(description != null) {
							partMasterEntity.setDescription(description.toString());
						}

						listNewPartMasterDataEntity.add(partMasterEntity);
						listPartNumber.add(sparePartNumber.toString());
					}
					
					
				}
//				chunkFile.delete();
				return equipSparePartMasterDataDataHandler.importBatch(listNewPartMasterDataEntity);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
//		chunkFile.delete();
		return resultBean;
	}

	@Override
	public String exportData( HttpServletRequest request, HttpServletResponse response, @RequestBody EquipSparePartMasterData obj) {
		List<EquipSparePartMasterDataEntity> list = equipSparePartMasterDataDataHandler.exportSelectByCondition(obj);		
	    String[] rowsName = new String[] {"备件编号","备件名称","规格型号","备注","备件类型","计量单位","单价","品牌商","关键参数","库存数量","各库存上限","各库存下线","创建人","创建时间","修改人","修改时间","预留"};    
	    List<Object[]> dataList = new ArrayList<Object[]>();  
	    for (int i = 0; i < list.size(); i++) {  
	        Object[] objs = new Object[rowsName.length];// 创建长度  
	        EquipSparePartMasterDataEntity PartMasterData= list.get(i);  
	        objs[0] = PartMasterData.getSparePartNumber();
	        objs[1] = PartMasterData.getSparePartName();
	        objs[2] = PartMasterData.getSparePartModel();
	        objs[3] = PartMasterData.getDescription();
	        objs[4] = PartMasterData.getSparePartType();
	        objs[5] = PartMasterData.getSparePartsUnit();
	        objs[6] = PartMasterData.getPrice();
	        objs[7] = PartMasterData.getSupplierName();
	        objs[8] = PartMasterData.getImportantParam();
	        objs[9] = PartMasterData.getTotalAmount();
	        objs[10] = PartMasterData.getUpperLimit();
	        objs[11] = PartMasterData.getLowerLimit();       
	        objs[12] = PartMasterData.getCreator();
	        objs[13] = PartMasterData.getCreationTime();
	        objs[14] = PartMasterData.getLastModifier();
	        objs[15] = PartMasterData.getLastModifiedTime();
	        objs[16] = "";
	        dataList.add(objs);  
	    }  
	      
	    String fileName = "备件主数据";  
	    //执行导出  
	    String filePath = ExportExcel.exportExcel(request,response,fileName, rowsName, dataList, "yyyy-MM-dd HH:mm:ss");  
		return filePath;
	}

}
